import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Input, 
  Button, 
  Space, 
  Tag, 
  Progress, 
  Modal, 
  Select,
  Row,
  Col,
  Statistic,
  Tooltip,
  Avatar,
  Form,
  App,
  Popconfirm,
  InputNumber
} from 'antd';
import { 
  SearchOutlined, 
  EyeOutlined, 
  BarChartOutlined,
  UserOutlined,
  ClockCircleOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import StudentDetail from './StudentDetail';
import StudentStats from './StudentStats';
import StudentLessons from './StudentLessons';
import './index.scss';
import { request } from '@/utils/api';

const { Search } = Input;
const { Option } = Select;

const StudentManagement = () => {
  
  const { message } = App.useApp();
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [searchParams, setSearchParams] = useState({
    keyword: '',
    status: 'active',
    sort: 'created_at',
    order: 'desc'
  });
  const [selectedStudent, setSelectedStudent] = useState(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [statsVisible, setStatsVisible] = useState(false);
  const [lessonsVisible, setLessonsVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [addLoading, setAddLoading] = useState(false);
  const [addForm] = Form.useForm();
  const [editVisible, setEditVisible] = useState(false);
  const [editLoading, setEditLoading] = useState(false);
  const [editForm] = Form.useForm();
  const [overallStats, setOverallStats] = useState({
    totalStudents: 0,
    activeStudents: 0,
    totalLessons: 0,
    totalRevenue: 0
  });
  const [deleteLoading, setDeleteLoading] = useState(false);

  // 获取学生列表
  const fetchStudents = async (params = {}) => {
    setLoading(true);
    try {
      const queryParams = new URLSearchParams({
        page: pagination.current,
        limit: pagination.pageSize,
        ...searchParams,
        ...params
      });
      const data = await request(`/student?${queryParams}`);
      if (data.code === 200) {
        setStudents(data.data.list);
        setPagination(prev => ({
          ...prev,
          total: data.data.total,
          current: data.data.page
        }));
      } else {
        message.error(data.message || '获取学生列表失败');
      }
    } catch (error) {
      console.error('获取学生列表失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 获取总体统计
  const fetchOverallStats = async () => {
    try {
      const data = await request('/student?limit=1');
      if (data.code === 200) {
        // 这里应该调用专门的统计接口，暂时使用模拟数据
        setOverallStats({
          totalStudents: data.data.total || 0,
          activeStudents: Math.floor((data.data.total || 0) * 0.85),
          newStudents: Math.floor((data.data.total || 0) * 0.15),
          avgLevel: 3.5
        });
      }
    } catch (error) {
      console.error('获取统计信息失败:', error);
    }
  };

  useEffect(() => {
    fetchStudents();
    fetchOverallStats();
  }, []);

  // 处理搜索
  const handleSearch = (value) => {
    setSearchParams(prev => ({ ...prev, keyword: value }));
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchStudents({ keyword: value, page: 1 });
  };

  // 处理筛选
  const handleFilter = (key, value) => {
    setSearchParams(prev => ({ ...prev, [key]: value }));
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchStudents({ [key]: value, page: 1 });
  };

  // 处理分页
  const handleTableChange = (paginationInfo) => {
    setPagination(prev => ({ ...prev, current: paginationInfo.current }));
    fetchStudents({ page: paginationInfo.current });
  };

  // 查看学生详情
  const handleViewDetail = (student) => {
    setSelectedStudent(student);
    setDetailVisible(true);
  };

  // 查看学生统计
  const handleViewStats = (student) => {
    setSelectedStudent(student);
    setStatsVisible(true);
  };

  // 查看学生课时管理
  const handleViewLessons = (student) => {
    setSelectedStudent(student);
    setLessonsVisible(true);
  };



  // 编辑学生
  const handleEditStudent = (student) => {
    setSelectedStudent(student);
    editForm.setFieldsValue({
      nickname: student.nickname,
      email: student.email,
      lesson_fee: student.lesson_fee,
      status: student.status,
      gender: student.gender,
      total_lessons: student.total_lessons,
      remark: student.remark
    });
    setEditVisible(true);
  };

  // 提交编辑学生
  const handleEditSubmit = async (values) => {
    setEditLoading(true);
    try {
      const data = await request(`/student/${selectedStudent.id}`, {
        method: 'PUT',
        body: JSON.stringify(values),
      });
      if (data.code === 200) {
        message.success('学生信息更新成功');
        setEditVisible(false);
        fetchStudents(); // 刷新列表
      } else {
        message.error(data.message || '更新学生信息失败');
      }
    } catch (error) {
      console.error('更新学生信息失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setEditLoading(false);
    }
  };

  // 新增学生
  const handleAddStudent = () => {
    setAddVisible(true);
    addForm.resetFields();
  };

  // 提交新增学生
  const handleAddSubmit = async (values) => {
    setAddLoading(true);
    try {
      const data = await request('/student', {
        method: 'POST',
        body: JSON.stringify(values),
      });
      if (data.code === 200) {
        message.success('学生添加成功');
        setAddVisible(false);
        fetchStudents(); // 刷新列表
        fetchOverallStats(); // 刷新统计
      } else {
        message.error(data.message || '添加学生失败');
      }
    } catch (error) {
      console.error('添加学生失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setAddLoading(false);
    }
  };

  // 删除学生
  const handleDeleteStudent = async (student) => {
    setDeleteLoading(true);
    try {
      const data = await request(`/student/${student.id}`, {
        method: 'DELETE',
      });
      if (data.code === 200) {
        message.success('学生删除成功');
        fetchStudents();
      } else {
        message.error(data.message || '删除失败');
      }
    } catch (error) {
      console.error('删除学生失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setDeleteLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '学生信息',
      key: 'student',
      render: (_, record) => (
        <div className="student-info">
          <Avatar 
            src={record.avatar} 
            icon={<UserOutlined />}
            size={40}
          />
          <div className="student-details">
            <div className="student-name">{record.nickname || record.username}</div>
            <div className="student-username">@{record.username}</div>
            <div className="student-contact">
              {record.email && <span>{record.email}</span>}
              {record.lesson_fee && <span>课时费: ¥{record.lesson_fee}</span>}
            </div>
          </div>
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '活跃' : '非活跃'}
        </Tag>
      )
    },
    {
      title: '购买课时',
      dataIndex: 'total_lessons',
      key: 'total_lessons',
      width: 100,
      render: (total_lessons) => (
        <span>{total_lessons || 0}</span>
      )
    },
    {
      title: '剩余课时',
      key: 'remaining_lessons',
      width: 120,
      render: (_, record) => {
        const remaining = parseFloat((record.total_lessons || 0) - (record.used_lessons || 0)).toFixed(2);
        return (
          <div className="remaining-lessons">
            <span className="lesson-number">{remaining} 课时（{remaining}小时）</span>
            <Progress 
              percent={record.total_lessons > 0 ? 
                Math.round(((record.total_lessons - parseFloat(remaining)) / record.total_lessons) * 100) : 0
              } 
              size="small" 
              showInfo={false}
            />
          </div>
        );
      }
    },
    {
      title: '注册时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 120,
      render: (date) => new Date(date).toLocaleDateString()
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="link" 
              icon={<EyeOutlined />} 
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          <Tooltip title="编辑学生">
            <Button 
              type="link" 
              icon={<EditOutlined />} 
              onClick={() => handleEditStudent(record)}
            />
          </Tooltip>
          <Tooltip title="查看统计">
            <Button 
              type="link" 
              icon={<BarChartOutlined />} 
              onClick={() => handleViewStats(record)}
            />
          </Tooltip>
          <Tooltip title="课时管理">
            <Button 
              type="link" 
              icon={<ClockCircleOutlined />} 
              onClick={() => handleViewLessons(record)}
            />
          </Tooltip>
          <Tooltip title="删除学生">
            
            <Popconfirm
              title={`确定要删除学生「${record.nickname || record.username}」吗？`}
              description='删除后不可恢复，且会删除该学生所有课时记录。'
              onConfirm={() => handleDeleteStudent(record)}
              okText="是"
              cancelText="否"
            >
              <Button 
                type="link" 
                icon={<DeleteOutlined />} 
                danger
                loading={deleteLoading}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      )
    }
  ];

  return (
    <div className="student-management">
      {/* 统计卡片 */}
      <Row gutter={16} className="stats-row">
        <Col span={6}>
          <Card>
            <Statistic
              title="总学生数"
              value={overallStats.totalStudents}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃学生"
              value={overallStats.activeStudents}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="新增学生"
              value={overallStats.newStudents}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均等级"
              value={overallStats.avgLevel}
              prefix={<UserOutlined />}
              precision={1}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索和筛选 */}
      <Card className="search-card">
        <Row gutter={16} align="middle">
          <Col span={8}>
            <Search
              placeholder="搜索学生姓名、用户名或邮箱"
              allowClear
              enterButton={<SearchOutlined />}
              onSearch={handleSearch}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="学生状态"
              value={searchParams.status}
              onChange={(value) => handleFilter('status', value)}
              style={{ width: '100%' }}
            >
              <Option value="active">活跃</Option>
              <Option value="inactive">非活跃</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              placeholder="排序方式"
              value={searchParams.sort}
              onChange={(value) => handleFilter('sort', value)}
              style={{ width: '100%' }}
            >
              <Option value="created_at">注册时间</Option>
              <Option value="last_login_at">最后登录</Option>
              <Option value="total_spent">消费金额</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              placeholder="排序方向"
              value={searchParams.order}
              onChange={(value) => handleFilter('order', value)}
              style={{ width: '100%' }}
            >
              <Option value="desc">降序</Option>
              <Option value="asc">升序</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Button 
              type="primary" 
              onClick={() => fetchStudents()}
            >
              刷新
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 学生列表 */}
      <Card 
        title="学生列表" 
        className="table-card"
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAddStudent}
          >
            新增学生
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={students}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
          }}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 学生详情弹窗 */}
      <Modal
        title="学生详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={800}
        destroyOnHidden
      >
        {selectedStudent && (
          <StudentDetail 
            student={selectedStudent} 
            onClose={() => setDetailVisible(false)}
          />
        )}
      </Modal>

      {/* 学生统计弹窗 */}
      <Modal
        title="学生统计"
        open={statsVisible}
        onCancel={() => setStatsVisible(false)}
        footer={null}
        width={1000}
        destroyOnHidden
      >
        {selectedStudent && (
          <StudentStats 
            student={selectedStudent} 
            onClose={() => setStatsVisible(false)}
          />
        )}
      </Modal>

      {/* 学生课时管理弹窗 */}
      <Modal
        title="学生课时管理"
        open={lessonsVisible}
        onCancel={() => setLessonsVisible(false)}
        footer={null}
        width={1200}
        destroyOnHidden
      >
        {selectedStudent && (
          <StudentLessons 
            student={selectedStudent} 
            onClose={() => setLessonsVisible(false)}
          />
        )}
      </Modal>

      {/* 新增学生弹窗 */}
      <Modal
        title="新增学生"
        open={addVisible}
        onCancel={() => setAddVisible(false)}
        footer={null}
        width={600}
        destroyOnHidden
      >
        <Form
          form={addForm}
          layout="vertical"
          onFinish={handleAddSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                ]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="nickname"
                label="昵称"
                rules={[
                  { required: true, message: '请输入昵称' }
                ]}
              >
                <Input placeholder="请输入昵称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input placeholder="请输入邮箱（可选）" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="lesson_fee"
                label="课时费"
                initialValue={0}
                rules={[
                  { required: true, message: '请输入课时费' },
                ]}
              >
                <Input 
                  type="number" 
                  placeholder="请输入课时费" 
                  min={0}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { min: 6, message: '密码至少6个字符' }
                ]}
              >
                <Input.Password placeholder="请输入密码（可选）" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                initialValue="active"
              >
                <Select>
                  <Option value="active">活跃</Option>
                  <Option value="inactive">非活跃</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="gender"
                label="性别"
                initialValue="unknown"
              >
                <Select>
                  <Option value="male">男</Option>
                  <Option value="female">女</Option>
                  <Option value="unknown">未知</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="total_lessons"
                label="购买课时"
                initialValue={0}
                rules={[
                  { type: 'number', min: 0, message: '课时数量不能为负数' }
                ]}
              >
                <InputNumber 
                  type="number" 
                  placeholder="请输入购买课时数" 
                  min={0}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="remark"
            label="备注"
          >
            <Input.TextArea 
              placeholder="请输入备注信息" 
              rows={3}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={addLoading}
              >
                确定
              </Button>
              <Button onClick={() => setAddVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑学生弹窗 */}
      <Modal
        title="编辑学生信息"
        open={editVisible}
        onCancel={() => setEditVisible(false)}
        footer={null}
        width={600}
        destroyOnHidden
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleEditSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="nickname"
                label="昵称"
                rules={[
                  { required: true, message: '请输入昵称' }
                ]}
              >
                <Input placeholder="请输入昵称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input placeholder="请输入邮箱（可选）" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="lesson_fee"
                label="课时费"
                initialValue={0}
              >
                <InputNumber 
                  placeholder="请输入课时费" 
                  min={0}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                initialValue="active"
              >
                <Select>
                  <Option value="active">活跃</Option>
                  <Option value="inactive">非活跃</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="gender"
                label="性别"
                initialValue="unknown"
              >
                <Select>
                  <Option value="male">男</Option>
                  <Option value="female">女</Option>
                  <Option value="unknown">未知</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="total_lessons"
                label="购买课时"
                initialValue={0}
              >
                <InputNumber 
                  placeholder="请输入购买课时数" 
                  min={0}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="remark"
            label="备注"
          >
            <Input.TextArea 
              placeholder="请输入备注信息" 
              rows={3}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={editLoading}
              >
                确定
              </Button>
              <Button onClick={() => setEditVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StudentManagement; 